<template>
  <el-row>
    <el-card>
      <el-form ref="searchForm" :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item :label="$t('systemModule.admin.table.userName')" prop="username">
          <el-input v-model="searchForm.username" clearable :placeholder="$t('common.input')" :maxlength="50" />
        </el-form-item>
        <el-form-item :label="$t('systemModule.admin.table.realName')" prop="description">
          <el-input v-model="searchForm.description" clearable :placeholder="$t('common.input')" :maxlength="50" />
        </el-form-item>
        <el-form-item :label="$t('systemModule.admin.table.mobile')" prop="phoneNumber">
          <el-input v-model="searchForm.phoneNumber" clearable :placeholder="$t('common.input')" :maxlength="50" />
        </el-form-item>
        <el-row>
          <el-button type="primary" @click="search">
            {{ $t('common.search') }}
          </el-button>
          <el-button @click="reset">
            {{ $t('common.reset') }}
          </el-button>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <el-row>
        <el-button type="primary" @click="add">
          {{ $t('systemModule.admin.add') }}
        </el-button>
      </el-row>
      <el-table
        v-loading="loading"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        :data="tableData"
        border
        :stripe="true"
        class="Top"
        style="width: 100%"
      >
        <el-table-column
          prop="username"
          :label="tableText['userName']"
          min-width="150"
        />
        <el-table-column
          prop="phoneNumber"
          :label="tableText['mobile']"
          min-width="150"
        />
        <el-table-column
          prop="description"
          :label="tableText['realName']"
          min-width="150"
        />
        <el-table-column
          :label="tableText['department']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ department(scope.row['departmentDTOS']) }}
          </template>
        </el-table-column>
        <el-table-column
          :label="tableText['role']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ roles(scope.row['roleOutputVOS']) }}
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          :label="$t('common.operate.name')"
          min-width="150"
        >
          <template slot-scope="scope">
            <el-button size="small" @click="handleClick(scope.row)">{{ $t('common.operate.edit') }}</el-button>
            <el-button type="danger" size="small" @click="deleteItem(scope.row)">{{ $t('common.operate.delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :current-page="searchForm.currentPage"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="searchForm.pageSize"
          :total="totalNumber"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <delete-dialog ref="delete-dialog" :delete-state="deleteState" :loading="deleteLoading" @change-delete="changeDelete" @delete-this="deleteThis" />
      <admin-setting :title="title" :show-dialog="editDialog" :roles-data="rolesData" :departs-tree="departsTree" :choose-item="chooseItem" @change-dialog="changeDialog" @edit-success="editSuccess" />
    </el-card>

  </el-row>
</template>

<script>
import { getAdministrator, deleteAdministrator, getRoles, getDepartment } from '@/api/system'
import deleteDialog from '@/components/delete/index.vue'
import adminSetting from '@/components/system/adminSetting.vue'
export default {
  name: 'Admin',
  components: {
    deleteDialog,
    adminSetting
  },
  data() {
    return {
      loading: true,
      tableData: [],
      deleteState: false,
      deleteLoading: false,
      editDialog: false,
      title: null,
      rolesData: null,
      departsTree: null,
      tableText: {},
      totalNumber: 0,
      searchForm: this.params(),
      chooseItem: {
        id: null,
        username: null,
        password: null,
        description: null,
        phoneNumber: null,
        roleIds: null,
        departmentIds: null
      }
    }
  },
  mounted() {
    this.tableText = this.$t('systemModule.admin.table')
    this.getData()
    this.getRolesData()
    this.getDeparts()
  },
  methods: {
    params() {
      return {
        currentPage: 1,
        pageSize: 10,
        enabled: 1,
        username: null,
        description: null,
        phoneNumber: null
      }
    },
    add() {
      this.title = this.$t('systemModule.admin.add')
      this.choose({})
      this.editDialog = true
    },
    search() {
      this.searchForm.currentPage = 1
      this.getData()
    },
    reset() {
      this.searchForm = this.params()
      this.getData()
    },
    handleClick(data) {
      const roleIds = []
      const departmentIds = []
      if (data && data['departmentDTOS'].length > 0) {
        data['departmentDTOS'].forEach(v => {
          departmentIds.push(v['id'])
        })
      }
      if (data && data['roleOutputVOS'].length > 0) {
        data['roleOutputVOS'].forEach(v => {
          roleIds.push(v['id'])
        })
      }
      const obj = {
        id: data['id'],
        username: data['username'],
        password: data['password'],
        description: data['description'],
        phoneNumber: data['phoneNumber'],
        roleIds: roleIds,
        departmentIds: departmentIds
      }
      this.title = this.$t('systemModule.admin.edit')
      this.choose(obj)
      this.editDialog = true
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.searchForm.currentPage = val
      this.getData()
    },
    getData() {
      this.loading = true
      getAdministrator(this.searchForm)
        .then(res => {
          this.loading = false
          if (res.success) {
            this.tableData = res.data
            this.totalNumber = res.page ? res.page['totalNumber'] : 0
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err.message)
        })
    },
    getRolesData() {
      const data = {
        currentPage: 1,
        pageSize: 10000
      }
      getRoles(data)
        .then(res => {
          if (res.success) {
            this.rolesData = res.data
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    // 根据对象渲染Tree
    getTreeNode(tree) {
      const arr = []
      if (!!tree && tree.length !== 0) {
        tree.forEach(item => {
          const obj = {}
          obj.label = item.name
          obj.id = item.id
          obj.children = this.getTreeNode(item.children)
          arr.push(obj)
        })
      }
      return arr
    },
    getDeparts() {
      getDepartment()
        .then(res => {
          if (res.success) {
            this.departsTree = this.getTreeNode(res.data)
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    roles(data) {
      if (!data || data.length === 0) {
        return
      }
      const arr = []
      data.forEach(v => {
        arr.push(v['name'])
      })
      return arr.join(',').substring(-1)
    },
    department(data) {
      if (!data || data.length === 0) {
        return
      }
      const arr = []
      const child = data.filter(v => {
        return v.parentId !== null
      })
      child.forEach(v => {
        const parentId = data.filter(item => {
          return item.id === v.parentId
        })
        arr.push(parentId && parentId[0] ? parentId[0].name + '-' + v.name : v.name)
      })
      return arr.join('  ,').substring(-1)
    },
    deleteItem(data) {
      this.chooseItem.id = data.id
      this.changeDelete(true)
    },
    changeDelete(param) {
      this.deleteState = param
    },
    changeDialog(param) {
      this.editDialog = param
      setTimeout(() => {
        this.choose({})
      }, 10)
    },
    editSuccess() {
      this.getData()
    },
    choose(param) {
      this.chooseItem.id = param.id
      this.chooseItem.username = param.username
      this.chooseItem.password = param.password
      this.chooseItem.description = param.description
      this.chooseItem.phoneNumber = param.phoneNumber
      this.chooseItem.roleIds = param.roleIds
      this.chooseItem.departmentIds = param.departmentIds
    },
    deleteThis() {
      this.deleteLoading = true
      const id = this.chooseItem.id
      deleteAdministrator(id)
        .then(res => {
          this.deleteLoading = false
          if (res.success) {
            this.$message.success(this.$t('common.tip.deleteSuccess'))
            this.changeDelete(false)
            this.getData()
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.deleteLoading = false
          this.$message.error(err.message)
        })
    }
  }

}
</script>

<style lang="scss" scoped>
.Top{
  margin-top: 10px
}
.el-card{
  margin: 10px
}
</style>
